package com.fablesoft.projectdatacollect.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.authentication.asynctask.AsyncFingerprint;
import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.CampaignRegisterResponse;
import com.fablesoft.projectdatacollect.bean.MemberBean;
import com.fablesoft.projectdatacollect.bean.MemberQueryBean;
import com.fablesoft.projectdatacollect.bean.MemberResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpUploadThread;
import com.fablesoft.projectdatacollect.sign.view.SignaturePad;
import com.fablesoft.projectdatacollect.util.BitmapUtil;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import android_serialport_api.FingerprintAPI;
import android_serialport_api.SerialPortManager;

public class SignFingerprintActivity extends BaseRequestActivity implements View.OnClickListener, SignaturePad.OnSignedListener, TextWatcher {
    private static final int INFO_REQUEST_CODE = 102;
    private static final int FINGERPRINT_CODE = 104;
    private static final int SIGN_IN_CODE = 106;
    private LinearLayout llRegister;
    private LinearLayout llNotRegister;
    private TextView tvName;
    private TextView tvPost;
    private TextView tvDepartment;
    private TextView tvFingerprintTip;
    private EditText etName;
    private EditText etPost;
    private EditText etDepartment;
    private RadioGroup rgTabRegister;
    private RadioGroup rgTabNotRegister;
    private RadioButton rbSignRegister;
    private RadioButton rbFingerprintRegister;
    private RadioButton rbSignNotRegister;
    private RadioButton rbFingerprintNotRegister;
    private SignaturePad signaturePad;
    private TextView signaturePadHint;
    private LinearLayout llClearSign;
    private Button btSignSubmit;
    private Button btFingerprintSubmit;
    private RelativeLayout rlFingerprintContent;
    private RelativeLayout rlSignContent;

    private boolean isRegister = false;// 是否已登记
    private int flag = 0; // 0:签字；1:指纹
    private String activityId;
    private MemberQueryBean member;

    private AsyncFingerprint asyncFingerprint;
    private ImageView fingerprintView;
    private byte[] fingerprintBytes;

    private boolean isSigned;
    private boolean isHasName;
    private boolean isHasFiner;

    private RadioGroup.OnCheckedChangeListener notRegisterListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.rb_sign_not_register:
                    flag = 0;
                    setSignOrFingerPrintLayout();
                    break;
                case R.id.rb_fingerprint_not_register:
                    flag = 1;
                    setSignOrFingerPrintLayout();
                    break;
            }
        }
    };

    private RadioGroup.OnCheckedChangeListener registerListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.rb_sign_register:
                    flag = 0;
                    setSignOrFingerPrintLayout();
                    break;
                case R.id.rb_fingerprint_register:
                    flag = 1;
                    setSignOrFingerPrintLayout();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_fingerprint);
        if (!SerialPortManager.getInstance().isOpen()
                && !SerialPortManager.getInstance().openSerialPort()) {
            ToastUtil.showToast(this, R.string.open_serial_fail);
        }
        isRegister = getIntent().getBundleExtra("data").getBoolean("isRegister");
        activityId = getIntent().getBundleExtra("data").getString("id");
        if (isRegister) {
            member = (MemberQueryBean) getIntent().getBundleExtra("data").getSerializable("member");
            flag = getIntent().getBundleExtra("data").getInt("flag");
        }
        initView();
        initData();
    }

    private void initView() {
        fingerprintView = (ImageView) findViewById(R.id.fingerprint_view);
        llRegister = (LinearLayout) findViewById(R.id.ll_register);
        llNotRegister = (LinearLayout) findViewById(R.id.ll_not_register);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvPost = (TextView) findViewById(R.id.tv_post);
        tvDepartment = (TextView) findViewById(R.id.tv_department);
        tvFingerprintTip = (TextView) findViewById(R.id.tv_fingerprint_tip);
        etName = (EditText) findViewById(R.id.et_name);
        etName.addTextChangedListener(this);
        etPost = (EditText) findViewById(R.id.et_post);
        etDepartment = (EditText) findViewById(R.id.et_department);
        rlFingerprintContent = (RelativeLayout) findViewById(R.id.rl_fingerprint_content);
        rlSignContent = (RelativeLayout) findViewById(R.id.rl_sign_content);

        llClearSign = (LinearLayout) findViewById(R.id.ll_clear_sign);
        btSignSubmit = (Button) findViewById(R.id.bt_sign_submit);
        btFingerprintSubmit = (Button) findViewById(R.id.bt_fingerprint_submit);
        llClearSign.setOnClickListener(this);
        btSignSubmit.setOnClickListener(this);
        btFingerprintSubmit.setOnClickListener(this);

        rgTabRegister = (RadioGroup) findViewById(R.id.rg_tab_register);
        rgTabNotRegister = (RadioGroup) findViewById(R.id.rg_tab_not_register);
        rgTabRegister.setOnCheckedChangeListener(registerListener);
        rgTabNotRegister.setOnCheckedChangeListener(notRegisterListener);
        rbSignRegister = (RadioButton) findViewById(R.id.rb_sign_register);
        rbFingerprintRegister = (RadioButton) findViewById(R.id.rb_fingerprint_register);
        rbSignNotRegister = (RadioButton) findViewById(R.id.rb_sign_not_register);
        rbFingerprintNotRegister = (RadioButton) findViewById(R.id.rb_fingerprint_not_register);

        signaturePadHint = (TextView) findViewById(R.id.signature_pad_hint);
        signaturePad = (SignaturePad) findViewById(R.id.signature_pad);

        signaturePad.setMaxWidth(12);
        signaturePad.setMinWidth(4);

        signaturePad.setOnSignedListener(this);

        setIsRegiserLayout();
        setSignOrFingerPrintLayout();

        View back = findViewById(R.id.back);
        back.setOnClickListener(this);

        if (asyncFingerprint == null) {
            asyncFingerprint = new AsyncFingerprint(MyApplication.getInstance()
                    .getHandlerThread().getLooper(), mHandler);
            asyncFingerprint
                    .setFingerprintType(FingerprintAPI.SMALL_FINGERPRINT_SIZE);
        }
    }

    private void initData() {
        if (!isRegister) {
            return;
        }
        if (member == null) {
            ToastUtil.showToast(this, "获取人员信息失败");
            finish();
        }
        tvName.setText(member.getPersonName());
        tvPost.setText(member.getPostName());
        tvDepartment.setText(member.getDepartmentName());
    }

    private void setIsRegiserLayout() {
        if (isRegister) {
            llRegister.setVisibility(View.VISIBLE);
            llNotRegister.setVisibility(View.INVISIBLE);
        } else {
            llRegister.setVisibility(View.INVISIBLE);
            llNotRegister.setVisibility(View.VISIBLE);
        }
    }

    private void setSignOrFingerPrintLayout() {
        if (flag == 0) {
            rlSignContent.setVisibility(View.VISIBLE);
            rlFingerprintContent.setVisibility(View.INVISIBLE);

        } else {
            rlSignContent.setVisibility(View.INVISIBLE);
            rlFingerprintContent.setVisibility(View.VISIBLE);
            rbFingerprintRegister.setChecked(true);
        }
    }

    private void setIsShowSubmitLayout() {
        if (flag == 0) {
            if (isSigned) {
                signaturePadHint.setVisibility(View.INVISIBLE);
            } else {
                signaturePadHint.setVisibility(View.VISIBLE);
            }
            if ((isHasName || isRegister) && isSigned) {
                btSignSubmit.setVisibility(View.VISIBLE);
            } else {
                btSignSubmit.setVisibility(View.INVISIBLE);
            }
        } else {
            if (isHasFiner) {
                tvFingerprintTip.setText(getResources().getString(R.string.tip_signature_success));
                fingerprintView.setBackgroundResource(R.drawable.bule_dash_frame_bg);
            }
            if ((isHasName || isRegister) && isHasFiner) {
                btFingerprintSubmit.setVisibility(View.VISIBLE);
            } else {
                btFingerprintSubmit.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AsyncFingerprint.SHOW_FINGER_IMAGE:
                    byte[] data = (byte[]) msg.obj;
                    Bitmap image = BitmapFactory.decodeByteArray(data, 0,
                            data.length);
                    fingerprintView.setImageBitmap(image);
                    fingerprintBytes = data;
                    isHasFiner = true;
                    setIsShowSubmitLayout();
                    if (asyncFingerprint != null) {
                        asyncFingerprint.setStop(true);
                    }
                    mHandler.removeMessages(FINGERPRINT_CODE);
                    break;
                case FINGERPRINT_CODE:
                    if (asyncFingerprint != null) {
                        asyncFingerprint.setStop(false);
                        asyncFingerprint.register();
                    }
                    break;
                case SIGN_IN_CODE:
                    BaseResponse response = (BaseResponse) msg.obj;
                    if (response == null || !response.getSuccess()){
                        ToastUtil.showToast(SignFingerprintActivity.this, "签到失败，请检查网络连接");
                        btFingerprintSubmit.setClickable(true);
                        btSignSubmit.setClickable(true);
                    } else {
                        ToastUtil.showToast(SignFingerprintActivity.this, "签到成功");
                        sendBroadcastReceiver();
                        SignFingerprintActivity.this.finish();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(FINGERPRINT_CODE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (asyncFingerprint != null) {
            asyncFingerprint.setStop(true);
        }
        mHandler.removeMessages(FINGERPRINT_CODE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (asyncFingerprint != null) {
            asyncFingerprint.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onRequestFinish(BaseResponse response) {
        Message msg = mHandler.obtainMessage();
        msg.obj = response;
        msg.what = INFO_REQUEST_CODE;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onNotLogin(BaseResponse response) {
        super.onNotLogin(response);
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)){
            Log.d("sglei-click", "点击过于频繁");
            return;
        }
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bt_sign_submit:
                btSignSubmit.setClickable(false);
                signIn(signaturePad.getSignatureBitmap());
                break;
            case R.id.bt_fingerprint_submit:
                btFingerprintSubmit.setClickable(true);
                signIn(fingerprintBytes);
                break;
            case R.id.ll_clear_sign:
                signaturePad.clear();
                break;
        }
    }

    private void signIn(Bitmap bitmap) {
        signIn(BitmapUtil.bitmapToBytes(bitmap));
    }

    private void signIn(byte[] file) {
        Map<String, Object> params = new HashMap<>();
        if (isRegister) {
            params.put("activityId", activityId);
            params.put("personId", member.getPersonId());
            params.put("inType", flag);
            params.put("isRegister", "1");
            params.put("personName", " ");
            params.put("postName", " ");
            params.put("orgName", " ");
        } else {
            params.put("activityId", activityId);
            params.put("personId", "-1");
            params.put("inType", flag);
            params.put("isRegister", "2");
            params.put("personName", etName.getText().toString());
            params.put("postName", TextUtils.isEmpty(etPost.getText().toString()) ? " " : etPost.getText().toString());
            params.put("orgName", TextUtils.isEmpty(etDepartment.getText().toString()) ? " " : etDepartment.getText().toString());
        }
        Log.d("sglei-upload", "签到参数：" + params);
        HttpUploadThread httpUploadThread = new HttpUploadThread(
                Config.CAMPAIGN_UNRECOGNIZED_URL, new HttpListener() {
            @Override
            public void onRequestFinish(BaseResponse response) {
                Message msg = mHandler.obtainMessage();
                msg.obj = response;
                msg.what = SIGN_IN_CODE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onNotLogin(BaseResponse response) {
                SignFingerprintActivity.this.onNotLogin(response);
            }
        }, file, params, CampaignRegisterResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpUploadThread);
    }

    @Override
    public void onStartSigning() {
        Log.d("sglei-sign", "Signature start");
        isSigned = true;
        setIsShowSubmitLayout();
    }

    @Override
    public void onSigned() {

    }

    @Override
    public void onClear() {
        isSigned = false;
        setIsShowSubmitLayout();
    }

    private void sendBroadcastReceiver() {
        Intent intent = new Intent();
        intent.setAction(CommonUtils.SIGN_BROADCAST_RECEIVER);
        sendBroadcast(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            isHasName = true;
        } else {
            isHasName = false;
        }
        setIsShowSubmitLayout();
    }
}
